package cn.seaboot.admin.mvc.response;

import cn.seaboot.admin.mvc.Problem;
import cn.seaboot.commons.core.FastJsonUtils;
import cn.seaboot.commons.file.ResponseWriter;
import org.jetbrains.annotations.NotNull;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 一个 ModelAndView 子类
 *
 * @author Mr.css
 * @version 2023-09-19 9:39
 */
public class FastJsonView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(@NotNull Map<String, Object> map
            , @NotNull HttpServletRequest request, @NotNull HttpServletResponse response) throws Exception {
        Object value = filterModel(map);
        response.getWriter().write(FastJsonUtils.toJSONString(value));
    }

    /**
     * 过滤掉一些不需要展示的数据
     *
     * fastjson 环境下，会产生无限递归
     *
     * @param map 参数
     * @return 最终结果
     */
    protected Object filterModel(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>(map.size());
        map.forEach((key, value) -> {
            if (!(value instanceof BindingResult) && !(value instanceof ModelAndView)) {
                result.put(key, value);
            }
        });
        return result;
    }

    public ModelAndView toModelAndView() {
        return new ModelAndView(this);
    }

    public void ofProblem(Problem problem) {
        if(problem.getType() != null){
            super.addStaticAttribute("type", problem.getType());
        }
        if(problem.getStatus() != null){
            super.addStaticAttribute("status", problem.getStatus());
        }
        if(problem.getTitle() != null){
            super.addStaticAttribute("title", problem.getTitle());
        }
        if (problem.getDetail() != null) {
            super.addStaticAttribute("detail", problem.getDetail());
        }
        if (problem.getInstance() != null) {
            super.addStaticAttribute("instance", problem.getInstance());
        }
        if (problem.getExtensions() != null) {
            super.addStaticAttribute("extensions", problem.getExtensions());
        }
    }
}
